﻿using M_Process.API.Appliction.Command.ProcessRouteCommand;
using M_Process.Domain;
using M_Process.Domain.DTO;
using M_Process.Repository.ProcessInterface;
using MediatR;

namespace M_Process.API.Appliction.CommandHandlers.ProcessRouteHandler
{
    /// <summary>
    /// 显示工艺信息
    /// </summary>
    public class ProcessRouteListCommandHandler : IRequestHandler<ProcessRouteListCommand, PageDTO<ProcessRoute>>
    {
        private readonly IProcessRouteRepository _processRouteRepository;
        public ProcessRouteListCommandHandler(IProcessRouteRepository processRouteRepository)
        {
            _processRouteRepository = processRouteRepository;
        }
        public async Task<PageDTO<ProcessRoute>> Handle(ProcessRouteListCommand request, CancellationToken cancellationToken)
        {
            var RouteList = await _processRouteRepository.GetAsync(d => !d.IsDeleted);
            if (!string.IsNullOrEmpty(request.ProcessPouteNumber))
            {
                RouteList = RouteList.Where(d => d.ProcessPouteNumber.Contains(request.ProcessPouteNumber)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProcessRouteName))
            {
                RouteList = RouteList.Where(d => d.ProcessRouteName.Contains(request.ProcessRouteName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.State))
            {
                bool Isnofo = false;
                if (request.State == "禁用")
                {
                    Isnofo = true;
                }
                RouteList = RouteList.Where(d => d.State == Isnofo).ToList();
            }
            if (request.PageSize == null)
            {
                request.PageSize = RouteList.Count();
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            PageDTO<ProcessRoute> page = new PageDTO<ProcessRoute>();
            page.TotalCount = RouteList.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)request.PageSize);
            page.list = RouteList.OrderByDescending(x => x.CreatedDate).Skip((int)(request.PageIndex - 1) * (int)request.PageSize).Take((int)request.PageSize).ToList();
            return page;
        }
    }
}
